<?php
namespace app\store\controller\food;

use app\store\controller\food\Controller;
use app\store\model\food\Order as OrderModel;
use app\store\model\food\ShopClerk as ShopClerkModel;
use app\store\model\food\Shop as ShopModel;
use app\store\model\food\Setting;
use think\facade\View;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use hema\delivery\Driver as Delivery;

/**
 * 订单管理
 */
class Order extends Controller
{
	
	
	/**
     * 全部退款订单列表
     */
    public function refund_list($shop_id = 0, string $search='')
    {
        return $this->getList('全部退款订单列表','refund',$shop_id,$search);
    }
	
	/**
     * 待退款订单列表
     */
    public function refund10_list($shop_id = 0, string $search='')
    {
        return $this->getList('待退款订单列表','refund10',$shop_id,$search);
    }
	
	/**
     * 已退款订单列表
     */
    public function refund20_list($shop_id = 0, string $search='')
    {
        return $this->getList('已退款订单列表','refund20',$shop_id,$search);
    }

    /**
     * 待收款订单列表
     */
    public function collection_list($shop_id = 0, string $search='')
    {
        return $this->getList('待收款订单列表','collection',$shop_id,$search);
    }

    /**
     * 待接单订单列表
     */
    public function shop_list($shop_id = 0, string $search='')
    {
        return $this->getList('待接单订单列表','shop',$shop_id,$search);
    }
	
    /**
     * 待发货订单列表
     */
    public function delivery_list($shop_id = 0, string $search='')
    {
        return $this->getList('待发货订单列表','delivery',$shop_id,$search);
    }

    /**
     * 待收货订单列表
     */
    public function receipt_list($shop_id = 0, string $search='')
    {
        return $this->getList('待收货订单列表','receipt',$shop_id,$search);
    }

    /**
     * 已完成订单列表
     */
    public function complete_list($shop_id = 0, string $search='')
    {
        return $this->getList('已完成订单列表','complete',$shop_id,$search);
    }

    /**
     * 被取消订单列表
     */
    public function cancel_list($shop_id = 0, string $search='')
    {
        return $this->getList('被取消订单列表','cancel',$shop_id,$search);
    }

    /**
     * 全部订单列表
     */
    public function all_list($shop_id = 0, string $search='')
    {
        return $this->getList('全部订单列表','all',$shop_id,$search);
    }

    /**
     * 订单列表
     */
    private function getList(string $title, string $dataType, $shop_id, string $search = '')
    {   
        if($this->shop_mode == 10){
           $shop_id = $this->shop_id;
        }
        $model = new ShopModel;
        $category = $model->getList(false);
        $model = new OrderModel;
        $list = $model->getList($dataType,$shop_id,0,$search);
        return View::fetch('index', compact('title','list','category','shop_id','search'));
    }

    /**
     * 订单详情
     */
    public function detail($id)
    {
        $detail = OrderModel::detail($id);
		$model = new ShopClerkModel;
		$clerk = $model->getAll($detail['shop_id']);
        $dv = new Delivery();
        $company = $dv->company();
        return View::fetch('detail', compact('detail','clerk','company'));
    }

    /**
     * 确认接单
     */
    public function shop($id)
    {
        $model = OrderModel::detail($id);
        if ($model->setShopStatus()) {
            return $this->renderSuccess('操作完成');
        }
        $error = $model->getError() ?: '操作失败';
        return $this->renderError($error);
    }

    /**
     * 设置外卖配送状态
     */
    public function deliveryStatus($id)
    {
        $model = OrderModel::detail($id);
        if ($model->setDeliveryStatus($this->postData('data'))) {
            return $this->renderSuccess('操作完成');
        }
        $error = $model->getError() ?: '操作失败';
        return $this->renderError($error);
    }

    /**
     * 确认发货
     */
    public function delivery($id)
    {
        $model = OrderModel::detail($id);
        $delivery = $this->postData('data');
        !isset($delivery['shop_clerk_id']) && $delivery['shop_clerk_id'] = '';
        if ($model->setDelivery($delivery['company'],$delivery['shop_clerk_id'])) {
            return $this->renderSuccess('操作完成');
        }
        $error = $model->getError() ?: '操作失败';
        return $this->renderError($error);
    }
	
	/**
     * 退款操作
     */
    public function refund($id)
    {
        $refund = $this->postData('data');
        $model = OrderModel::detail($id);
        if ($model->refund($refund['is_refund'])) {
            return $this->renderSuccess('操作成功');
        }
        $error = $model->getError() ?: '操作失败';
        return $this->renderError($error);
    }

    /**
     * 确认收到用户付款
     */
    public function collection($id)
    {
        $model = OrderModel::detail($id);
        if ($model->collection()) {
            return $this->renderSuccess('操作成功');
        }
        $error = $model->getError() ?: '操作失败';
        return $this->renderError($error);
    }

    /**
     * 导出订单
     */
    public function export_order()
    {
        $data = $this->postData('time');
        $star = strtotime($data['star'].' 00:00:00');
        $end = strtotime($data['end'].' 23:59:59');
        $model = new OrderModel;
        $list = $model->with(['goods' => ['image', 'spec', 'goods'], 'address', 'shop', 'table','delivery'])
            ->where('create_time','>',$star)
            ->where('create_time','<',$end)
            ->select();
        # 实例化 Spreadsheet 对象
        $spreadsheet = new Spreadsheet();
        # 获取活动工作薄
        $sheet = $spreadsheet->getActiveSheet();
        //文字左右居中对齐
        $styleArray = [
            'alignment' => [
                'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
            ],
        ];
        //黑色边框
        $borderStyleArray = [
            'borders' => [
                'allBorders' => [
                    'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN//细边框
                ],
            ],
        ];

        $values = Setting::getItem('other',$this->applet_id);
        if($values['order_export'] == 'col'){
            //设置单元格宽度
            $sheet->getColumnDimension('A')->setWidth(8);
            $sheet->getColumnDimension('B')->setWidth(30);
            $sheet->getColumnDimension('C')->setWidth(8);
            $sheet->getColumnDimension('D')->setWidth(8);
            $sheet->getColumnDimension('E')->setWidth(8);
            $n = 0;
            foreach ($list as $vo) {
                $n++;
                $sheet->mergeCells('A'.$n.':E'.$n); //合并单元格
                $sheet->getCell('A'.$n)->setValue($vo['shop']['shop_name'] . '（' . $vo['order_status']['text'] . '）');
                $sheet->getStyle('A'.$n)->getFont()->setBold(true)->setSize(14);//字体加粗字号14
                $sheet->getStyle('A'.$n)->applyFromArray($styleArray);//水平居中
                $sheet->getRowDimension($n)->setRowHeight(30);//设置行高30
                $n++;
                $x = $n;
                $sheet->mergeCells('A'.$n.':E'.$n);
                $sheet->getCell('A'.$n)->setValue('单号：'.$vo['order_no'].'  时间：' . $vo['create_time']);
                $n++;
                $sheet->mergeCells('A'.$n.':E'.$n);
                $title = $vo['source']['text'] . ' # ';
                if($vo['order_mode']['value']==10 AND $vo['row_no'] <> ''){
                    $title .= '堂食'.$vo['row_no'].'号';
                }
                if($vo['order_mode']['value']==10 AND $vo['row_no'] == ''){
                    $title .= '餐桌'.$vo['table']['table_name'].' - '.$vo['people'].'人';
                }
                if($vo['order_mode']['value']==20){
                    $title .= '外卖'.$vo['row_no'].'号';
                }
                if($vo['order_mode']['value']==30){
                    $title .= '自取'.$vo['row_no'].'号 - ' . $vo['arrive_time']['text'];
                }
                $sheet->getCell('A'.$n)->setValue($title);
                $n++;
                $sheet->setCellValue('A'.$n,'编号');
                $sheet->setCellValue('B'.$n,'商品');
                $sheet->setCellValue('C'.$n,'单价');
                $sheet->setCellValue('D'.$n,'数量');
                $sheet->setCellValue('E'.$n,'退单');
                $sheet->getStyle('A'.$n.':E'.$n)->getFont()->setBold(true);
                $y = $n;
                $num = 0;//商品列表编号
                foreach ($vo['goods'] as $goods) {
                    $n++;
                    $num++;
                    $sheet->setCellValue('A'.$n,$num);
                    if(empty($goods['goods_attr'])){
                        $name = $goods['goods_name'];
                    }else{
                        $name = $goods['goods_name'] . '/' . $goods['goods_attr'];  
                    }
                    $sheet->setCellValue('B'.$n,$name);
                    $sheet->setCellValue('C'.$n,$goods['goods_price']);
                    $sheet->setCellValue('D'.$n,$goods['total_num']);
                    $sheet->setCellValue('E'.$n,$goods['refund_num']);
                }
                $sheet->getStyle('A'.$y.':E'.$n)->applyFromArray($styleArray);
                $n++;
                $sheet->mergeCells('A'.$n.':E'.$n);
                $sheet->getCell('A'.$n)->setValue('备注：'.$vo['message'].'  口味：' . $vo['flavor']);
                $n++;
                $sheet->mergeCells('A'.$n.':E'.$n);
                if($vo['order_mode']['value']==20){
                    $title = '地址：' . $vo['address']['district'] . ' ' . $vo['address']['detail'] . ' ' . $vo['address']['name'] . ' ' .$vo['address']['phone'];
                }else{
                    $title = '用户：' . $vo['user']['nickname'] . ' ID：' . $vo['user']['user_id'];
                }
                $sheet->getCell('A'.$n)->setValue($title);
                $n++;
                $sheet->mergeCells('A'.$n.':E'.$n);
                $sheet->getCell('A'.$n)->setValue('付款状态：'.$vo['pay_status']['text'].'  应付金额：￥' . $vo['pay_price']);
                $sheet->getStyle('A'.$x.':E'.$n)->applyFromArray($borderStyleArray);
            }
        }else{
            //设置单元格宽度
            $sheet->getColumnDimension('A')->setWidth(16);
            $sheet->getColumnDimension('B')->setWidth(17);
            $sheet->getColumnDimension('C')->setWidth(12);
            $sheet->getColumnDimension('D')->setWidth(29);
            $sheet->getColumnDimension('E')->setWidth(5);
            $sheet->getColumnDimension('F')->setWidth(16);
            $sheet->getColumnDimension('G')->setWidth(5);
            $sheet->getColumnDimension('H')->setWidth(5);
            $sheet->getColumnDimension('I')->setWidth(5);
            $sheet->getColumnDimension('J')->setWidth(10);
            $sheet->getColumnDimension('K')->setWidth(10);
            $sheet->getColumnDimension('L')->setWidth(15);
            $sheet->getColumnDimension('M')->setWidth(40);
            $sheet->mergeCells('E1:I1'); //合并单元格
            $sheet->setCellValue('A1','订单编号');
            $sheet->setCellValue('B1','下单时间');
            $sheet->setCellValue('C1','门店名称');
            $sheet->setCellValue('D1','订单类型');
            $sheet->setCellValue('E1','商品信息');
            $sheet->setCellValue('J1','付款状态');
            $sheet->setCellValue('K1','订单状态');
            $sheet->setCellValue('L1','客户备注');
            $sheet->setCellValue('M1','用户信息');
            $sheet->getStyle('A1:M1')->getFont()->setBold(true);//字体加粗
            $sheet->getStyle('A1:M1')->applyFromArray($styleArray);//水平居中

            $n = 1; //表格行数
            foreach ($list as $vo) {
                $n++;
                $sheet->getCell('A'.$n)->setValue((string)$vo['order_no']);
                $sheet->getCell('B'.$n)->setValue($vo['create_time']);
                $sheet->getCell('C'.$n)->setValue($vo['shop']['shop_name']);
                if($vo['order_mode']['value']==10 AND $vo['row_no'] <> ''){
                    $title = '堂食'.$vo['row_no'].'号';
                }
                if($vo['order_mode']['value']==10 AND $vo['row_no'] == ''){
                    $title = '堂食'.$vo['table']['table_name'];
                }
                if($vo['order_mode']['value']==20){
                    $title = '外卖'.$vo['row_no'].'号';
                }
                if($vo['order_mode']['value']==30){
                    $title = '自取'.$vo['row_no'].'号 - ' . $vo['arrive_time']['text'];
                }
                $sheet->getCell('D'.$n)->setValue($title);
                $sheet->getCell('E'.$n)->setValue('编号');
                $sheet->getCell('F'.$n)->setValue('名称');
                $sheet->getCell('G'.$n)->setValue('单价');
                $sheet->getCell('H'.$n)->setValue('数量');
                $sheet->getCell('I'.$n)->setValue('退单');
                $sheet->getCell('J'.$n)->setValue($vo['pay_status']['text']);
                $sheet->getCell('K'.$n)->setValue($vo['order_status']['text']);
                $sheet->getCell('L'.$n)->setValue($vo['message']);
                if($vo['order_mode']['value']==20){
                    $user = '地址：' . $vo['address']['district'] . ' ' . $vo['address']['detail'] . ' ' . $vo['address']['name'] . ' ' .$vo['address']['phone'];
                }else{
                    $user = '用户：' . $vo['user']['nickname'] . ' ID：' . $vo['user']['user_id'];
                }
                $sheet->getCell('M'.$n)->setValue($user);
                $sheet->getStyle('A'.$n.':M'.$n)->applyFromArray($styleArray);//水平居中
                $sheet->getStyle('A'.$n.':M'.$n)->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);//垂直居中
                $s = $n; //合并开始位置
                $num = 0; //编号
                foreach ($vo['goods'] as $goods) {
                    $n++;
                    $num++;
                    $sheet->setCellValue('E'.$n,$num);
                    if(empty($goods['goods_attr'])){
                        $name = $goods['goods_name'];
                    }else{
                        $name = $goods['goods_name'] . '/' . $goods['goods_attr'];  
                    }
                    $sheet->setCellValue('F'.$n,$name);
                    $sheet->setCellValue('G'.$n,$goods['goods_price']);
                    $sheet->setCellValue('H'.$n,$goods['total_num']);
                    $sheet->setCellValue('I'.$n,$goods['refund_num']);
                    $sheet->getStyle('E'.$n.':I'.$n)->applyFromArray($styleArray);//水平居中
                }
                $sheet->mergeCells('A'.$s.':A'.$n); //合并单元格
                $sheet->mergeCells('B'.$s.':B'.$n); //合并单元格
                $sheet->mergeCells('C'.$s.':C'.$n); //合并单元格
                $sheet->mergeCells('D'.$s.':D'.$n); //合并单元格
                $sheet->mergeCells('J'.$s.':J'.$n); //合并单元格
                $sheet->mergeCells('K'.$s.':K'.$n); //合并单元格
                $sheet->mergeCells('L'.$s.':L'.$n); //合并单元格
                $sheet->mergeCells('M'.$s.':M'.$n); //合并单元格
            }
            $sheet->getStyle('A1:M'.$n)->applyFromArray($borderStyleArray);
        }    
        # Xlsx类 将电子表格保存到文件
        $writer = new Xlsx($spreadsheet);
        $file_name = $data['star'] . '-' .$data['end'] .'.xls';
        //$writer->save('temp/' . $file_name);//保存在本地
        
       // 客户端文件下载
        header('Content-Type:application/vnd.ms-excel');
        header('Content-Disposition:attachment;filename='.$file_name);
        header('Cache-Control:max-age=0');
        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xls');
        $writer->save('php://output');
    }
}
